<template>
  <span v-if="isShow" class="perm">
    <slot></slot>
  </span>
</template>

<script>
  import roleTree from '@/tools/menuTree';
  export default {
    name: 'perm',
    props: ['label'],
    mounted() {
      let roleMap = this.$store.state.allRoleMap;
      if (roleMap.valid) return;
      let obj = {};
      obj.valid = true;
      this.setRoleMap(roleTree, obj);
      this.$store.commit('initAllRoleMap', obj);
    },
    computed: {
      isShow: function () {
        let menu = this.$store.state.allRoleMap;
        if (!menu.valid) return;
        let perm = menu[this.label];
        if (!perm) return true;
        if (perm === 'show') return true;
        let menus = this.$store.state.permissions;
        if (!perm.includes(',')) {
          return menus.indexOf(perm) !== -1;
        }
        let perms = perm.split(',');
        return perms.some(s => menus.indexOf(s) !== -1);
      }
    },
    methods: {
      setRoleMap(menus, obj) {
        menus.forEach(i => {
          if (i.children) {
            this.setRoleMap(i.children, obj);
            obj[i.id] = i.perms;
          } else {
            obj[i.id] = i.perms;
          }
        });
      }
    }
  };
</script>
